package com.xiyou.week05.binarySearch;

/**
 * 911. 在线选举
 *
 * @ClassName：TopVotedCandidate
 * @Author：西柚
 * @Date：2022/1/28 2:24 下午
 * @Versiion：1.0
 */
public class TopVotedCandidate {

    int[] persons;
    int[] times;
    int[][] memo;

    /**
     * 输入：
     * ["TopVotedCandidate", "q", "q", "q", "q", "q", "q"]
     * [[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]]
     * 输出：
     * [null, 0, 1, 1, 0, 0, 1]
     * <p>
     * 解释：
     * TopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]);
     * topVotedCandidate.q(3); // 返回 0 ，在时刻 3 ，票数分布为 [0] ，编号为 0 的候选人领先。
     * topVotedCandidate.q(12); // 返回 1 ，在时刻 12 ，票数分布为 [0,1,1] ，编号为 1 的候选人领先。
     * topVotedCandidate.q(25); // 返回 1 ，在时刻 25 ，票数分布为 [0,1,1,0,0,1] ，编号为 1 的候选人领先。（在平局的情况下，1 是最近获得投票的候选人）。
     * topVotedCandidate.q(15); // 返回 0
     * topVotedCandidate.q(24); // 返回 0
     * topVotedCandidate.q(8); // 返回 1
     * <p>
     * 链接：https://leetcode-cn.com/problems/online-election
     *
     * @param persons
     * @param times
     */
    public TopVotedCandidate(int[] persons, int[] times) {
        this.persons = persons;
        this.times = times;
        memo = new int[times.length][2];
        pre();
    }

    public int q(int t) {
        int timePosistion = binarySearch(t);
        if (times[timePosistion] <= t) {
            return memo[timePosistion][0];
        } else {
            return memo[timePosistion - 1][0];
        }
    }

    public void pre() {
        int maxPerson = -1;
        int maxNum = -1;
        int[] nums = new int[5001];
        for (int i = 0; i < times.length; i++) {
            nums[persons[i]]++;
            if (nums[persons[i]] >= maxNum) {
                maxNum = nums[persons[i]];
                maxPerson = persons[i];
            }
            memo[i][0] = maxPerson;
            memo[i][1] = maxNum;
        }
    }


    public int binarySearch(int t) {
        int left = 0;
        int right = times.length - 1;
        while (left < right) {
            int mid = (left + right) / 2;
            if (times[mid] == t) {
                return mid;
            } else if (times[mid] > t) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }

    public static void main(String[] args) {
        int[] persons = new int[]{0, 1, 1, 0, 0, 1, 0};
        int[] times = new int[]{0, 5, 10, 15, 20, 25, 30};
        TopVotedCandidate topVotedCandidate = new TopVotedCandidate(persons, times);
        System.out.println(topVotedCandidate.q(25));

    }
}
/**
 * Your TopVotedCandidate object will be instantiated and called as such:
 * TopVotedCandidate obj = new TopVotedCandidate(persons, times);
 * int param_1 = obj.q(t);
 */